package com.cloud.code.socket;

import java.io.*;
import java.net.Socket;
import java.util.Vector;

public class UserSocketServiceThread extends Thread {

    private Vector<UserSocketServiceThread> vector = new Vector();
    private String name;
    private Socket socket;
    private ObjectInputStream objectInputStream;
    private ObjectOutputStream objectOutputStream;

    public UserSocketServiceThread() {
    }

    public UserSocketServiceThread(Vector<UserSocketServiceThread> vector, Socket socket) {
        this.socket = socket;
        this.vector = vector;
        vector.add(this);
    }

    @Override
    public void run() {
        try {
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());

            System.out.println("客户端：" + socket.getLocalAddress().getHostAddress());

            Boolean flag = true;
            while (flag) {
                Message message = (Message) objectInputStream.readObject();
                MsgType msgType = message.getMsgType();
                System.out.println(socket.getLocalAddress().getHostAddress());
                switch (msgType) {
                    case SEND:
                        System.out.println("send msg");
                        for (UserSocketServiceThread vector : vector) {

                            System.out.println(vector.name);
                            if (message.getToUser().equalsIgnoreCase(vector.name) && vector != this) {
                                vector.objectOutputStream.writeObject((message));
                                break;
                            }
                        }
                        break;
                    case LGOIN:
                        System.out.println("welcome login:" + message.getFromUser());
                        name = message.getFromUser();
                        System.out.println(name);
                        objectOutputStream.writeObject(new Message("welcome login :" + message.getFromUser(), null, "system", message.getFromUser()));
                        break;
                }
            }
            objectInputStream.close();
            objectOutputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
